package com.xiaoma.lock.spin;

import java.util.concurrent.atomic.AtomicReference;

/**实现一个自旋锁
 * @author xiaomacdut
 * @date 2020年3月3日 下午12:54:35
 */
public class MySpinLock{
    
    AtomicReference<Thread> reference = new AtomicReference<>();
    
    public void lock(){
        System.out.println(Thread.currentThread().getName() + "  want to get lock");
        // 没有set成功，说明已经有线程设置成功了
        while(!reference.compareAndSet(null, Thread.currentThread())){
            System.out.println(Thread.currentThread().getName() + "  try to get Lock");
        }
        System.out.println(Thread.currentThread().getName() + "  got the lock");
    }
    
    public void unLock(){
        System.out.println(Thread.currentThread().getName() + "  want to  Unlock");
        reference.compareAndSet(Thread.currentThread(), null);
        System.out.println(Thread.currentThread().getName() + "  Unlock ");
    }
    
}
